/** 本地缓存服务类默认存在 localStorage */
export class LocalCache {
  /**
   * @param key 缓存 key
   * @param value 缓存值，数据类型必须支持 Json 序列化
   */
  setCache<T = any>(key: string, value: T): boolean;
  /**
   * @param key 缓存 key
   * @param value 缓存值，数据类型必须支持 Json 序列化
   * @param isSession 是否存在 session storage
   */
  setCache<T = any>(key: string, value: T, isSession: boolean): boolean;

  setCache<T = any>(key: string, value: T, isSession: boolean = false): boolean {
    try {
      const val = JSON.stringify(value);
      if (isSession) {
        window.sessionStorage.setItem(key, val);
      } else {
        window.localStorage.setItem(key, val);
      }
    } catch (error) {
      return false;
    }
    return true;
  }

  /**
   * @param key 缓存 key
   */
  getCache<T = any>(key: string): T;
  /**
   *
   * @param key 缓存 key
   * @param isSession 是否 session storage
   */
  getCache<T = any>(key: string, isSession: boolean): T;

  getCache<T = any>(key: string, isSession = false) {
    let result: T | null = null;
    if (isSession) {
      const val = window.sessionStorage.getItem(key);
      if (val) {
        result = JSON.parse(val);
      }
    } else {
      const val = window.localStorage.getItem(key);
      if (val) {
        result = JSON.parse(val);
      }
    }
    return result;
  }

  clearCache(): void;
  /**
   * 清空缓存
   * @param isSession
   */
  clearCache(isSession: boolean): void;

  clearCache(isSession: boolean = false) {
    if (isSession) {
      window.sessionStorage.clear();
    } else {
      window.localStorage.clear();
    }
  }
}
